package per.hnvcam.searchext.parser.impl;

import java.io.IOException;
import java.io.InputStream;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.html.HtmlParser;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

import per.hnvcam.net.http.HTTPConnection;
import per.hnvcam.searchext.parser.WebParser;

/**
 * Created by IntelliJ IDEA.
 * User: violon
 * Date: 4/9/11
 * Time: 4:45 PM
 * To change this template use File | Settings | File Templates.
 */

public class WebParserImpl implements WebParser {

   private HtmlParser htmlParser;

   private HTTPConnection httpConnection;

   private ParseContext parseContext;

   private Metadata metadata;

   private ContentHandler contentHandler;

   public WebParserImpl(HtmlParser htmlParser, HTTPConnection httpConnection, ParseContext parseContext, Metadata metadata) {
      this.htmlParser = htmlParser;
      this.httpConnection = httpConnection;
      this.parseContext = parseContext;
      this.metadata = metadata;
   }

   public void parse(String url) throws IOException {
      InputStream httpStream = null;
      try {
         httpStream = httpConnection.doGet(url);
         htmlParser.parse(httpStream, contentHandler, metadata, parseContext);
      } catch (IOException e) {
         e.printStackTrace();
      } catch (SAXException e) {
         e.printStackTrace();
      } catch (TikaException e) {
         e.printStackTrace();
      } finally {
         httpStream.close();
      }
   }

   public void setContentHandler(ContentHandler contentHandler) {
      this.contentHandler = contentHandler;
   }
}
